<?php
/*
date('o') was added in PHP 5.1.0
*/

/*
4 functions as hook!

define('WDIR',dirname(__FILE__));
function getDailyFile($t) {
    return WDIR.'/daily/'.date('Y-m-d',$t).'.tar';
}
function getWeeklyFile($t) {
    return WDIR.'/weekly/'.date('o-W',$t).'.tar';
}
function getMonthlyFile($t) {
    return WDIR.'/monthly/'.date('Y-m',$t).'.tar';
}
function archiveToday($t) {
}
*/

define('TODAY_TIME',time());
define('DAY_SECS',86400);

if (!defined('STORE_NUM_OF_DAYS')) {
    define('STORE_NUM_OF_DAYS',7);
}

if (!defined('STORE_NUM_OF_WEEKS')) {
    define('STORE_NUM_OF_WEEKS',4);
}


    
foreach (array('getDailyFile','getWeeklyFile','getMonthlyFile') as $v) {
    $d=dirname($v(TODAY_TIME));
    if (!file_exists($d)) {
        if (!mkdir($d,0600,true)) {
            echo 'fail to mkdir(',$d,")\n";
            exit(1);
        }
    }
}

$today_file=getDailyFile(TODAY_TIME);
if (!file_exists($today_file)) {
    archiveToday(TODAY_TIME);
}

$week_end_offset=STORE_NUM_OF_WEEKS*7+STORE_NUM_OF_DAYS;
for ($i=STORE_NUM_OF_DAYS;$i<100;$i++) {
    $current_time=TODAY_TIME-DAY_SECS*$i;
    $daily_file=getDailyFile($current_time);
    $weekly_file=getWeeklyFile($current_time);
    $monthly_file=getMonthlyFile($current_time);


    if (file_exists($daily_file)) {
        if ($i<=$week_end_offset && !file_exists($weekly_file)) {
            system('mv '.$daily_file.' '.$weekly_file);
        } else if (!file_exists($monthly_file)) {
            system('mv '.$daily_file.' '.$monthly_file);
        } else {
            echo 'rm '.$daily_file.' ... ';
            system('rm -f '.$daily_file);
            echo "ok\n";
        }
    }

    if ($i>$week_end_offset && file_exists($weekly_file)) {
        echo 'rm '.$weekly_file.' ... ';
        system('rm -f '.$weekly_file);
        echo "ok\n";
    }
}
